﻿package net.wangit.framework.license;

import java.io.IOException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;

import net.wangit.Path;
import net.wangit.util.ArrayUtil;
import net.wangit.util.Checker;
import net.wangit.util.DateUtil;
import net.wangit.util.ServerUtil;
import net.wangit.util.StringUtil;
import net.wangit.util.SystemUtil;
import net.wangit.util.XMLUtil;


/**
 * license管理类
 * 
 * @author watson Feb 14, 2010
 */
public final class LManager {

	private static final String PATH = Path.getHomePath() + "/license.xml";

	private LManager() {
	}

	public static boolean validate() {
		L license;
		try {
			license = L.fromXML(PATH);
		} catch (Exception e) {
			System.out.println("could not load license!");
			return false;
		}
		if (!validateSignature(license)) {
			System.out.println("The license is not valid.");
			return false;
		}
		if (!validateIp(license)) {
			System.out.println("The IP is not valid:");
			ArrayUtil.print(ServerUtil.getIps());
			return false;
		}
		Date expiresDate = license.getExpiration();
		if (expiresDate != null) {
			long now = System.currentTimeMillis();
			if (expiresDate.getTime() < now) {
				System.out.println("The license is expired.");
				return false;
			}
		}
		return true;
	}

	private static boolean validateSignature(L l) {
		X509EncodedKeySpec pubKeySpec;
		String publicKey = "308201b73082012c06072a8648ce3804013082011f02818100fd7f53811d75122952df4a9c2eece4e7f611b7523cef4400c31e3f80b6512669455d402251fb593d8d58fabfc5f5ba30f6cb9b556cd7813b801d346ff26660b76b9950a5a49f9fe8047b1022c24fbba9d7feb7c61bf83b57e7c6a8a6150f04fb83f6d3c51ec3023554135a169132f675f3ae2b61d72aeff22203199dd14801c70215009760508f15230bccb292b982a2eb840bf0581cf502818100f7e1a085d69b3ddecbbcab5c36b857b97994afbbfa3aea82f9574c0b3d0782675159578ebad4594fe67107108180b449167123e84c281613b7cf09328cc8a6e13c167a8b547c8d28e0a3ae1e2bb3a675916ea37f0bfa213562f1fb627a01243bcca4f1bea8519089a883dfe15ae59f06928b665e807b552564014c3bfecf492a0381840002818019921f7f71ba621b351428e7002ed836013a46222567abde7a7fecaaaed22ad1f4769efc87855719c05d1656b56fa249fc073cd77cba12d77c61616b581993dcb10cf4770f8f7852b17a785912895ca24bda703853ebfa1b887398946ec5b9c0076286caa3886443101f5eeae5162c0122b12f0251d6ee047872159bf6a165be";
		byte pub[] = StringUtil.decodeHex(publicKey);
		pubKeySpec = new X509EncodedKeySpec(pub);
		Signature sig;
		try {
			KeyFactory keyFactory = KeyFactory.getInstance("DSA");
			java.security.PublicKey pubKey = keyFactory
					.generatePublic(pubKeySpec);
			sig = Signature.getInstance("DSA");
			sig.initVerify(pubKey);
			sig.update(l.getFingerprint());
			return sig.verify(StringUtil.decodeHex(l.getSignature()));
		} catch (Exception e) {
			return false;
		}
	}

	private static boolean validateIp(L l) {
		String ip = l.getIp();
		if (Checker.isEmpty(ip))
			return true;
		String localIp = ServerUtil.getLocalIp();
		return ip.equals(localIp) || "127.0.0.1".equals(localIp);
	}

	public static void main(String[] args) {
		L l = new L("cms", "Wangit", "1.0", SystemUtil.getMACAddress());
		l.setExpiration(DateUtil.getDate("2012-12-31"));

		try {
			/*
			 * 生成密钥对 KeyPairGenerator keyPairGen =
			 * KeyPairGenerator.getInstance("DSA"); keyPairGen.initialize(1024);
			 * KeyPair keyPair = keyPairGen .genKeyPair(); PublicKey publicKey =
			 * keyPair.getPublic(); // 公钥 PrivateKey privateKey =
			 * keyPair.getPrivate(); // 私钥 String pubKey =
			 * StringUtil.encodeHex(publicKey.getEncoded()); String priKey =
			 * StringUtil.encodeHex(privateKey.getEncoded());
			 * System.out.println("pubKey:"); System.out.println(pubKey);
			 * System.out.println("priKey:"); System.out.println(priKey);
			 */

			byte[] privateKey = StringUtil
					.decodeHex("3082014b0201003082012c06072a8648ce3804013082011f02818100fd7f53811d75122952df4a9c2eece4e7f611b7523cef4400c31e3f80b6512669455d402251fb593d8d58fabfc5f5ba30f6cb9b556cd7813b801d346ff26660b76b9950a5a49f9fe8047b1022c24fbba9d7feb7c61bf83b57e7c6a8a6150f04fb83f6d3c51ec3023554135a169132f675f3ae2b61d72aeff22203199dd14801c70215009760508f15230bccb292b982a2eb840bf0581cf502818100f7e1a085d69b3ddecbbcab5c36b857b97994afbbfa3aea82f9574c0b3d0782675159578ebad4594fe67107108180b449167123e84c281613b7cf09328cc8a6e13c167a8b547c8d28e0a3ae1e2bb3a675916ea37f0bfa213562f1fb627a01243bcca4f1bea8519089a883dfe15ae59f06928b665e807b552564014c3bfecf492a0416021425de6011f93bc97ab470269e11868893181eabbc");
			// 构造PKCS8EncodedKeySpec对象
			PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(
					privateKey);
			// KEY_ALGORITHM 指定的加密算法
			KeyFactory keyFactory = KeyFactory.getInstance("DSA");
			// 取私钥匙对象
			PrivateKey pk = keyFactory.generatePrivate(pkcs8KeySpec);
			// 用私钥对信息生成数字签名
			Signature sig = Signature.getInstance("DSA");
			sig.initSign(pk);
			sig.update(l.getFingerprint());
			String signature = StringUtil.encodeHex(sig.sign());
			// System.out.println("signature:");
			// System.out.println(signature);
			l.setSignature(signature);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			XMLUtil.write(L.toXML(l), "E:/license.xml");
			System.out.println("成功生成授权！");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
